#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int append = 0;
const char *filename = NULL;

static int parse_options(int argc, char *argv[]) {
    int opt = 0;
    while ((opt = getopt(argc, argv, "a")) != -1) {
        switch (opt)
        {
        case 'a':
            append = 1;
            break;
        
        default:
            errno = EINVAL;
            return -1;
        }
    }

    if (optind >= argc) {
        errno = EINVAL;
        return -1;
    }
    filename = argv[optind];

    return 0;
}

void show_usage() {
    fprintf(stdout, "Usage: tee [-a] <filename>\n");
}

int main(int argc, char *argv[]) {
    int res = 0;
    int fd_file;
    char buf[BUFSIZ];
    ssize_t nread;
    ssize_t nwrite;
    res = parse_options(argc, argv);
    if (res != 0) {
        show_usage();
        return res;
    }

    fd_file = open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0644);
    if (fd_file == -1) {
        perror("open");
        return -1;
    }

    while ((nread = read(STDIN_FILENO, buf, sizeof(buf))) > 0) {
        nwrite = write(fd_file, buf, nread);
        if (nwrite == -1) {
            perror("write");
            return -1;
        }
        if (nwrite != nread) {
            fprintf(stderr, "short write: %zd != %zd\n", nwrite, nread);
            return -1;
        }
        nwrite = write(STDOUT_FILENO, buf, nread);
        if (nwrite == -1) {
            perror("write");
            return -1;
        }
        if (nwrite != nread) {
            fprintf(stderr, "short write: %zd != %zd\n", nwrite, nread);
            return -1;
        }
    }
    if (nread == -1) {
        perror("read");
        return -1;
    }

    close(fd_file);
    return 0;
}